package 函数式编程.scala

import scala.annotation.tailrec

object MyModule {

  def abs(n: Int): Int = if (n < 0) -n else n

  private def formatAbs(x: Int): String = {
    val msg = "The absolute value of %d is %d"
    msg.format(x, abs(x))
  }

  def main(args: Array[String]): Unit = {
    println(formatAbs(-42))
    println(formatFactorial(5))
    println(fib(9))
    println(formatResult("ABS", 8, abs))
  }

  def factorial(n: Int): Int = {
    @tailrec
    def go(n: Int, acc: Int): Int = {
      if (n < 1) acc else go(n - 1, n * acc)
    }
    //初始化
    go(n, 1)
  }

  private def formatFactorial(n: Int): String = {
    val msg = "The factorial of %d is %d"
    msg.format(n, factorial(n))
  }

  private def formatResult(title: String, n: Int, f: Int => Int): String = {
    val msg = "The %s of %d is %d"
    msg.format(title, n, f(n))
  }

  /**
   * 求第n个斐波那契数
   */
  private def fib(n: Int): Int = {
    if (n == 1) 0 else if (n == 2 || n == 3) 1 else fib(n - 2) + fib(n - 1)
  }

  /**
   * 数组中查找元素
   */
  def findFirst[A](as: Array[A], f: A => Boolean): Int = {
    @tailrec
    def loop(n: Int): Int = {
      if (n >= as.length) -1
      else if (f(as(n))) n
      else loop(n + 1)
    }
    //初始化
    loop(0)
  }

  //  def compose[A, B, C](f: B => C, g: A => B): A => C = {
  //
  //  }
  val ex1: List[Double] = Nil

}
